<?php

namespace app\admin\controller\qudao;

use app\admin\controller\Controller;
use app\admin\model\zhiye\Company as CompanyModel;
use app\admin\model\article\Category as CategoryModel;
use think\Db;
use think\Session;

/**
 * 销售人员控制器
 */
class Company extends Controller{
    public function index(){
        $model = new CompanyModel;
        $companyId=Session::get('yoshop_adminuser')['user']['company_id'];
        $list = $model->getList($this->request->get(),$companyId);
		
        return $this->fetch('index', compact('list'));
    }
    /**
     * 添加人员
     */
    public function add(){
        $model = new CompanyModel;
        if(empty($this->postData('company')['name'])){
            return $this->fetch('add');
        }
        $data=$this->postData('company');
        //判断该手机号已添加过
        $userInfo=Db::name('yonghui_user')->where(['phone'=>$data['phone']])->find();
        if($userInfo){
            return $this->renderError($model->getError() ?: '该手机号已添加过');
        }
        if($data['password']!=$data['repassword']){
            return $this->renderError($model->getError() ?: '两次输入的密码不一致，请重新输入');
        }
        //所属公司id
        $data['companyId']=Session::get('yoshop_adminuser')['user']['company_id'];
        $data['createTime']=time();
        $data['password']=md5($data['password']);
        $data['status']=1;
        $data['type']=3;
        $insert=$model->add($data);
        if($insert){
            return $this->renderSuccess('添加成功', url('zhiye.company/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 更新人员
     */
    public function edit($id){
        //人员详情
        $model = CompanyModel::detail($id);
        if (!$this->request->isAjax()){
            return $this->fetch('edit', compact('model'));
        }
        //判断该手机号已添加过
        $userInfo=Db::name('yonghui_user')->where(['phone'=>$this->postData('company')['phone']])->find();
        if($userInfo&&$id!=$userInfo['id']){
            return $this->renderError($model->getError() ?: '该手机号已添加过');
        }
        if ($model->edit($this->postData('company'))) {
            return $this->renderSuccess('更新成功', url('zhiye.company/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除人员
     */
    public function delete($id){
        $model = CompanyModel::detail($id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }
    /*
     * 恢复
     */
    public function recover($id){
        $model = CompanyModel::detail($id);
        if (!$model->recover()) {
            return $this->renderError($model->getError() ?: '恢复失败');
        }
        return $this->renderSuccess('恢复成功');
    }
}